<%@ page language="java" contentType="text/html; charset=UTF-8"
  pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt"%>
<%
  String path = request.getContextPath();
  String basePath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort()
      + path + "/";
%>
<!DOCTYPE html>
<html lang="en">
<head>
<base href="<%=basePath%>">
<!-- 下拉框 -->
<link rel="stylesheet" href="static/ace/css/chosen.css" />

<link href="plugins/kindeditor/themes/simple/simple.css" type="text/css" rel="stylesheet">
<link rel="stylesheet" href="static/ace/css/datepicker.css" />
<link href="//cdn.bootcss.com/ionicons/2.0.1/css/ionicons.min.css" rel="stylesheet">
<!-- jsp文件头和头部 -->
<%@ include file="../index/top.jsp"%>
<style>
.disabled{color:#000;cursor: default;}
.disabled:hover{color:#000;text-decoration:none;}
</style>
</head>
<body class="no-skin">
  <!-- /section:basics/navbar.layout -->
  <div class="main-container" id="main-container">
    <!-- /section:basics/sidebar -->
    <div class="main-content">
      <div class="main-content-inner">
        <div class="page-content">
          <div class="row">
            <div class="col-xs-12">
              <form action="goods/${msg }.do" name="goodsForm"
                id="goodsForm" method="post">
                <c:if test="${goods.id !=null}">
                  <input type="hidden" name="id" id="id" value="${goods.id }" />
                </c:if>
                 <input type="hidden" id="state" value="${state}" />
                  <c:if test="${paramList !=null}">
                   <input type="hidden" id="pl" value="${paramList}" />
                 </c:if>
                 <c:if test="${msg!='editG'}">
                   <input type="hidden" name="attr" id="attr" value="" />
                   <input type="hidden" name="param" id="param" value="" />
                 </c:if>
                <div id="zhongxin" style="padding-top: 13px;">
                  <table id="table_report"
                    class="table table-striped table-bordered table-hover">
                    <tr>
                      <td
                        style="width: 79px; text-align: right; padding-top: 13px;">标题:</td>
                      <td><input type="text" name="title"
                        id="title" value="${goods.title }"
                        maxlength="100" placeholder="这里输入标题" title="标题"
                        style="width: 98%;" /></td>
                    </tr>
                    <tr>
                      <td
                        style="width: 79px; text-align: right; padding-top: 13px;">描述:</td>
                      <td><textarea rows="5" cols="10"
                          id="describe" name="describe" maxlength="250"
                          style="width: 98%;" title="商品描述">${goods.describe }</textarea></td>
                    </tr>
                    <tr>
                      <td
                        style="width: 30px; text-align: right; padding-top: 13px;">分类:</td>
                      <td><a href="javascript:void(0)"
                        class="chooseClass">选择分类</a> <span
                        id="className">${goods.className }</span> <%--  &nbsp; 所属品牌  &nbsp;<span id="brandName">${goods.brandName }</span> --%>
                        <input type="hidden" name="classId" id="classId"
                        value="${goods.classId }" /> <%-- <input type="hidden" name="brandId" id = "brandId" value="${goods.brandId}"/> --%>
                      </td>
                    </tr>
                     <tr>
                      <td
                        style="width: 85px; text-align: right; padding-top: 15px;">缩略图:</td>
                      <td><a href="javascript:void(0)"
                        class="onePicUpload">上传图片</a> <c:if test="${not empty goods.thumb}">
                          <a href='${goods.thumb }' target='_blank'><img src='${goods.thumb }' width='80' height='50' /></a>
                        </c:if> <input type="hidden" name="thumb" id="thumb"
                        value="${goods.thumb }" /></td>
                    </tr>
                    <tr>
                      <td
                        style="width: 85px; text-align: right; padding-top: 15px;">白天商品图:</td>
                      <td><a href="javascript:void(0)"
                        class="onePicUpload">上传图片</a> <c:if test="${not empty goods.thumb_day}">
                          <a href='${goods.thumb_day }' target='_blank'><img src='${goods.thumb_day }' width='80' height='50' /></a>
                        </c:if> <input type="hidden" name="thumb_day" id="thumb_day"
                        value="${goods.thumb_day }" /></td>
                    </tr>
                     <tr>
                      <td
                        style="width: 85px; text-align: right; padding-top: 13px;">黑夜商品图:</td>
                      <td><a href="javascript:void(0)"
                        class="onePicUpload">上传图片</a> <c:if
                          test="${not empty goods.thumb_night}">
                          <a href='${goods.thumb_night }' target='_blank'><img src='${goods.thumb_night }' width='80' height='50' /></a>
                        </c:if> <input type="hidden" name="thumb_night" id="thumb_night"
                        value="${goods.thumb_night }" /></td>
                    </tr>

                    <tr>
                      <td
                        style="width: 79px; text-align: right; padding-top: 13px;">展示图片:</td>
                      <td><a href="javascript:void(0)"
                        class="picFileUpload">上传图片</a> <input
                        type="hidden" id="picture" name="picture" id="picture"
                        value="${goods.picture }" /></td>
                    </tr>
                    <tr>
                      <td
                        style="width: 79px; text-align: right; padding-top: 13px;">商品详情:</td>
                      <td>
                          <textarea class="content" style="width: 1000px; height: 400px;"
                          name="content" id="content">${goods.content}</textarea>
                          </td>
                    </tr>
                    
                  </table>
                   <table id="table_report1"
                    class="table table-striped table-bordered table-hover">
                       <tr>
                        <td style="text-align: center;" colspan="10">
                        <c:if test="${state!=00 }">
                          <a class="btn btn-mini btn-primary"
                          onclick="save();">保存</a>
                        </c:if>
                           <a class="btn btn-mini btn-danger"
                          onclick="top.Dialog.close();">取消</a>
                        </td>
                      </tr>
                    </table>
                </div>
                <div id="zhongxin2" class="center" style="display: none">
                  <br /> <br /> <br /> <br /> <img
                    src="static/images/jiazai.gif" /><br />
                  <h4 class="lighter block green"></h4>
                </div>
              </form>
            </div>
            <!-- /.col -->
          </div>
          <!-- /.row -->
        </div>
        <!-- /.page-content -->
      </div>
    </div>
    <!-- /.main-content -->
  </div>


  <!-- /.main-container -->
  <!-- basic scripts -->
  <!-- 页面底部js¨ -->
  <%@ include file="../index/foot.jsp"%>
  <!-- ace scripts -->
  <script src="static/ace/js/ace/ace.js"></script>
  <!-- inline scripts related to this page -->
  <!-- 下拉框 -->
  <script src="static/ace/js/chosen.jquery.js"></script>
  <!--提示框-->
  <script type="text/javascript" src="static/js/jquery.tips.js"></script>
  <script type="text/javascript" src="static/js/common/file_upload.js"></script>
  <script type="text/javascript" src="plugins/kindeditor/kindeditor-all.js"></script>
  <script type="text/javascript" src="plugins/kindeditor/lang/zh_CN.js"></script>
  <script type="text/javascript" src="static/laydate/laydate.js"></script>
  <script type="text/javascript" src="static/js/provincial.municipal.league.js"></script>
</body>
<script type="text/javascript">
  $(top.hangge());
  var itemAddEditor ;
  var currentIndex = 0;
  //页面初始化完毕后执行此方法
  var min_ratio=$("#min_ratio").val();
  var max_ratio=$("#max_ratio").val();
  
  $("#isParam").change(function() { 
    if(document.getElementById("isParam").checked){
    	$("#plus").show()
    }else{
    	$("#plus").hide()
    	 $("#table_report1 tr:gt(0)").remove();
    }
  });
  $("#plus1").click(function() { 
      var tr='<tr><td style="width: 79px; text-align: center; padding-top: 13px;">商品参数:</td><td >'+
          '<span class="ion-ios-minus-outline btn-minus" style="font-size: 20px;margin-top:7px; display:inline-block;"></span>&emsp;'+
            '<input type="text" name="params" maxlength="4" style="width: 10%;" placeholder="输入参数名称"/>'+
            '<input type="text" name="values" maxlength="64" style="width: 75%;" placeholder="输入参数值"/>'+
            '<input type="number" name="sorts" maxlength="64" value=99 style="width: 10%;" placeholder="参数排列序号"/>'+
            '<input type="hidden" name="state1" value="03"/>'+
            ' <input type="hidden" name="pid" value="0"/>'+
            '</td></tr>';
      $("#table_report1").append(tr);
      //currentIndex+=1;
    });
  
  $("#plus").click(function() { 
      var tr='<tr><td style="width: 79px; text-align: center; padding-top: 13px;">商品参数:</td><td >'+
          '<span class="ion-ios-minus-outline btn-minus" style="font-size: 20px;margin-top:7px; display:inline-block;"></span>&emsp;'+
            '<input type="text" name="params" maxlength="4" style="width: 10%;" placeholder="输入参数名称"/>'+
            '<input type="text" name="values" maxlength="64" style="width: 75%;" placeholder="输入参数值"/>'+
            '<input type="number" name="sorts" maxlength="64" value=99 style="width: 10%;" placeholder="参数排列序号"/></td></tr>';
      $("#table_report1").append(tr);
      //currentIndex+=1;
    });
  
  
  $('body').on('click','.btn-minus',function(){
	  var parent = $(this).parents('tr')
	  parent.remove()
  })
  
   $('body').on('click','.btn-minuss',function(){
	  var parent = $(this).parents('tr')
	  parent.hide();
	  parent.find("input[name=state1]").val('01');
  }) 
  
  $('.but-d').change(function(){
	 
	 $(this).find("input[name=state1]").val('02');
  })
  
  
  
  $(function(){
	 var state=$("#state").val();
	 if(state!=01){
		 $("#table_report").find("input,button,textarea,select").attr("disabled", "disabled"); 
	 }
	  if($("#pl").val()!=''){
		  $("input[name='checkbox']").attr("checked","true"); 
		  $("#plus1").show()
	  }
    
    var type =$("#isAdvanceState").val();
    if(type=='01'){
      $('.advanceEle').show()
      $('.payment').show()
    }else{
      $('.advanceEle').hide()
      $('.payment').hide()
    }
    $("#isPack").on("change",function(){
      var value = $(this).val();
      if($.trim(value) == '00'){
        $("#transitPrice").attr("readonly",false);
      }else{
        $("#transitPrice").attr("readonly",true);
        $("#transitPrice").val("0.00")
      }
    })
    
    SpecificationsBtn();
    //创建富文本编辑器
    TAOTAO.kingEditorParams = {
      //指定上传文件参数名称
      filePostName  : "uploadFile",
      //指定上传文件请求的url。
      uploadJson : '<%=basePath%>pic/upload',
      //上传类型，分别为image、flash、media、file
      dir : "image",
      extraFileUploadParams:{isCom:"01",width:800,height:800,quality:0.8,end:"view"}
    }
    
    TAOTAO.kingEditorAutoParams = {
        //指定上传文件参数名称
        filePostName  : "uploadFile",
        //指定上传文件请求的url。
        uploadJson : '<%=basePath%>pic/upload',
        //上传类型，分别为image、flash、media、file
        dir : "image",
        extraFileUploadParams:{isCom:"01",width:200,height:200,quality:1,end:"thumb"}
      }
    
    goodsAddEditor = TAOTAO.createEditor("#goodsForm [name=content]");
    //初始化类目选择和图片上传器
    TAOTAO.initPicUpload($("input[name=picture]").val());
    TAOTAO.initOnePicUpload($("input[name=thumb]").val());
    
    
    $('body').on('click','.imageButton',function(){
      var id=$("#id").val();
      var picture=$("#picture").val();
      var imgsrc=$(this).parent('li').find("img").attr("src");
      var _this = $(this);
      var others = $(this).parent('li').siblings()
      
      var newPicture="";
      if(picture.indexOf((imgsrc+',')) >-1){
        newPicture=picture.replace((imgsrc+','),'');
      }else if(picture.indexOf((','+imgsrc)) > -1){
        newPicture=picture.replace((','+imgsrc),'');
      }
      $.ajax({
        url:"<%=basePath%>pic/pictureDelete",
        type:"post",
        async:true,
        dataType:"text",
        data:{"id":id,"newPicture":newPicture,"imgsrc":imgsrc,"state":"00"},
        success : function(data) {
          if(data == "success"){
            _this.parent('li').remove();
            var html =''
            for(var i=0;i<others.length;i++){
            	var $item = $(others[i])
            	var val = $item.find('img').attr('src')
            	html+=val+','
            }
            console.log(html)
            
            $("#picture").val(html); 
          }
        },error : function(XMLHttpRequest, textStatus){
          alealert(textStatus);
        }
      });   
    });
  });
  $("#costPrice").change(function(){
    $("#agentPrice").val(($(this).val()*1.1).toFixed(2));
  });
  $("#price").change(function(){
    if($("#isSales").val()=='00'||'${msg}'=='saveG'){
      $("#realPrice").val($(this).val());
    }
  });
  
  $("#isSales").change(function(){
    var tempPrice=$("#tempPrice").val();
    if($(this).val()=='00'&&'${msg}'=='editG'){
      $("#realPrice").val($("#price").val());
    }else if($(this).val()=='01'&&'${msg}'=='editG'){
      $("#realPrice").val(tempPrice);
    }
    
  });
  
  function countDiscount(){
    if($.trim($("#marketPrice").val())==""){
      alert("市场价为空无法计算");
      return false;
    }
    if($.trim($("#bidPrice").val())==""){
      alert("进货价价为空无法计算");
      return false;
    } 
    if($("#marketPrice").val()==0){
      alert("市场价不能等于0");
      return false;
    }
    if($("#bidPrice").val()==0){
      alert("进货价不能等于0");
      return false;
    }
    var discount=(toDecimal($("#bidPrice").val())/($("#marketPrice").val())*10).toFixed(2);
    if(Number(discount)<=0||Number(discount)>=10){
      alert("折扣比例不正确，请检查进货价和市场价");
      $("#discount").val("");
      return false;
    }
    $("#discount").val(discount);
    if(Number(discount)>max_ratio){
      $("#isPointsBuy").val("00");
      $("#changePoints").val(0);
      $.ajax({  
         type:'post',  
         url:'goods/getReturnPoints.do',
         async:false, 
         data:{"discount":discount},   
         success:function(data){ 
           if("failed"==data){
             alert("没有找到对应返还比例");
             return false;
           }
           if($("#isSales").val()=='00'){$("#changePrice").val($("#price").val()); $("#returnPoints").val(parseInt($("#price").val()*Number(data)/100));}
           else{$("#changePrice").val($("#realPrice").val());$("#returnPoints").val(parseInt($("#realPrice").val()*Number(data)/100));}
           }
         });
    }else if(min_ratio<Number(discount)&&Number(discount)<=max_ratio){
      $("#isPointsBuy").val("01");
      $("#returnPoints").val(0);
      if($("#isSales").val()=='00'){
      $("#changePoints").val(parseInt($("#price").val()*(1-Number(discount)/10)/(1-min_ratio/10)));
      $("#changePrice").val(Number($("#price").val())-Number($("#changePoints").val()));
      }else{
      $("#changePoints").val(parseInt($("#realPrice").val()*(1-Number(discount)/10)/(1-min_ratio/10)));
      $("#changePrice").val(Number($("#realPrice").val())-Number($("#changePoints").val()));  
      }
    }else{
      $("#isPointsBuy").val("01");
      $("#changePrice").val(0);
      $("#returnPoints").val(0);
      if($("#isSales").val()=='00'){$("#changePoints").val(Math.ceil($("#price").val()));}
      else{$("#changePoints").val(Math.ceil($("#realPrice").val()));}
    }
  }
  function save(){
	   	if($.trim($("#title").val())==""){
          alert("请输入商品标题");
          return false;
        }
		if($.trim($("#classId").val())==""){
	          alert("请选择商品类别");
	          return false;
	    }
		 if($.trim($("#thumb").val())==""){
	            alert("请上传商品缩略图");
	            return false;
	        }
        if($.trim($("#thumb_day").val())==""){
            alert("请上传商品白天商品图");
            return false;
        }
        if($.trim($("#thumb_night").val())==""){
            alert("请上传商品黑夜商品图");
            return false;
        }
        if($.trim($("#picture").val())==""){
            alert("请上传商品展示图");
            return false;
        }
        if(goodsAddEditor.isEmpty()){
      	   alert("请上传商品详情");
           return false;
        } 
      goodsAddEditor.sync(); 
      $("#goodsForm").submit();
      $("#zhongxin").hide();
      $("#zhongxin2").show(); 
  }
  $(".chooseClass").on("click",function(){
     var diag = new top.Dialog();
     diag.Drag=true;
     diag.Title ="选择商品分类";
     diag.URL = '<%=basePath%>classify/toClassifyPage.do';
    diag.Width = 500;
    diag.Height = 500;
    diag.CancelEvent = function() {
      diag.close();
    }, diag.OKEvent = function() {
      var child = diag.innerFrame.contentWindow.document;
     var classId= $(child).find("#classId").val()
     $.ajax({
           url:"<%=basePath%>classify/getClassifyIsP",
           type:"post",
           async:true,
           dataType:"text",
           data:{"classId":classId},
           success : function(data) {
              if("success" ==data){
            	alert("请选择二级分类!");
              }else{
            	  $("#classId").val(classId);
                  $("#className").html($(child).find("#className").val());
              }
           }
         });
      diag.close();
    };//点击确定后调用的方法
    diag.show();
  })
  
  
  function getInputVal($parent){
 		  var $table = $parent.find('.js-goods-standard');
 		  var ths = $table.find('thead th')
 		  var trs = $table.find('tbody tr')
 		  var html=''
 		  var data=[{
 			 key:[],
 			 value:[]
 		  }]
 		  for(var i=1;i<ths.length;i++){
 			  var val = ths.eq(i).text()
 			  data[0].key.push(val)
 		  } 		  
    	  for(var i=0;i<trs.length;i++){
    		  var tds = trs.eq(i).find('td')
    		  var text ='';
    		  data[0].value.push([])
    		  for(var j=1;j<tds.length;j++){
    			  var val =tds.eq(j).find('input[name=stock]').val()
    			  var index = tds.eq(j).attr('data-index')
    			  if(index){
    				  if(j === tds.length-2){
    					  text +=index
    				  }else{
    					  text +=index+'-'
    				  }
    			  }
    			  if(!!val){
    				  data[0].value[i].push($.trim(val));
    			  }
    			 
    		  }
    		  data[0].value[i].push(text);
    	  }
    	  var data=JSON.stringify(data);
    	 //$("#param").val(data);
    	 
    	 return data;
 	  }
  
  
   $("#selectSpec").on("click",function(){
	   if($(this).hasClass('disabled')){
		   return false;
	   }
	 var $this = $(this);
     var diag = new top.Dialog();
     diag.Drag=true;
     diag.Title ="添加规格";
     diag.URL = '<%=basePath%>goods/toGoodsSpec.do';
     diag.Width = 1200;
     diag.Height = 500;
     diag.CancelEvent = function() {
     diag.close();
    }, diag.OKEvent = function() {
      var child = diag.innerFrame.contentWindow.document;
      //[{"key":["规格1","库存"],"value":[["1","p1"]]}]
      
      var param = getInputVal($(child))
      
      var attr=$(child).find("#attr").val();
      //var param=$(child).find("#param").val();
      
      console.log(param)
      
      if(attr !="" &&param != ""){
        $("#attr").val(attr);
        $("#param").val(param)
        $("#gS").html("已添加")
        $this.addClass('disabled')
      }
      diag.close();
    };//点击确定后调用的方法
    diag.show();
  })
  
  
  
  
  $("#selectUnitSpan").on("click",function(){
	  	 var $this = $(this);
	     var isSelectUnit = $this.find("input").val();
	     if(isSelectUnit == '00'){
	    	 $this.find("input").prop("checked",true); 
	      }else{
	    	 $this.find("input").prop("checked",false); 
	      }
	     var diag = new top.Dialog();
	     diag.Drag=true;
	     diag.Title ="多单位设置";
	     diag.URL = '<%=basePath%>goods/unit.do';
	     diag.Width = 500;
	     diag.Height = 500;
	     diag.CancelEvent = function() {
	      diag.close();
	      if(isSelectUnit == '00'){
	    	  $this.find("input").prop("checked",false); 
	      }else{
	    	  $this.find("input").prop("checked",true); 
	      }
	    }, diag.OKEvent = function() {
	      var child = diag.innerFrame.contentWindow.document;
	      diag.close();
	    };//点击确定后调用的方法
	    diag.show(); 
	  
  })
  
  //decimal类型判断
  function isDecimal(item) {
    var obj = $(item);
    if (obj.length > 0) {
      if ($(obj).val() != null && typeof ($(obj).val()) != "undefined") {
        var str = $(obj).val().toString();
        if (str != "") {
          var pattern = '^-?[1-9]\\d*$|^-?0\\.\\d*$|^-?[1-9]\\d*\\.\\d*$';
          var reg = new RegExp(pattern, 'g');
          if (reg.test(str)) {
            return true;
          } else {
            if (str.match(/[^0-9\.-]/g) != null) {
              if (str.match(/[^0-9\.-]/g).length > 0) {
                $(item).val('');
              }
            }
          }
        }
      }
    }
    return false;
  }
  //检查是否为正整数
  function isInt(a) {
    var reg = /^\d+$/;
    return reg.test(a);
  }
  var SpecificationsBtn = function() {
    $(".SpecificationsBtn").on("click", function() {

    })
  }
  //检查输入对象的值是否符合整数格式
  function isInteger(str) {
    var regu = /^[-]{0,1}[0-9]{1,}$/;
    return regu.test(str);
  }

  var removeImg = function() {

  }

  function toDecimal(x) {
    var f = parseFloat(x);
    if (isNaN(f)) {
      return;
    }
    f = Math.round(x * 100) / 100;
    return f;
  }

  function addTr(tr) {
    var type = $("#isAdvanceState").val();
    if (type == '01') {
      $('.advanceEle').show()
      $('.payment').show()
    } else {
      $('.advanceEle').hide()
      $('.payment').hide()
    }
  }

</script>
</html>